/**
 * @Title ExamActivity.java
 * @Package cn.sinokj.party.building.adapter
 * @Description TODO(用一句话描述该文件做什么)
 * @author azzbcc Email: azzbcc@sina.com
 * @date 创建时间 2016年7月13日 下午3:51:37
 * @version V1.0
 **/
package cn.sinokj.party.chineseFourParty.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.base.BaseActivity;
import cn.sinokj.party.chineseFourParty.bean.ExamQuestion;
import cn.sinokj.party.chineseFourParty.bean.ExamQuestionAnswered;
import cn.sinokj.party.chineseFourParty.bean.ExamTopic;
import cn.sinokj.party.chineseFourParty.service.HttpConstants;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.utils.time.TimeUtils;
import cn.sinokj.party.chineseFourParty.view.dialog.DialogShow;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;


/**
 * @author azzbcc Email: azzbcc@sina.com
 * @ClassName ExamActivity
 * @Description 试题界面
 * @date 创建时间 2016年7月13日 下午3:51:37
 **/
public class ExamActivity extends BaseActivity {
    private static final int INIT_DATA = 1;
    private static final int START_EXAM = 2;
    private static final int CONTINUE_EXAM = 3;
    private static final int FINISH_EXAM = 4;
    @BindView(R.id.title)
    public TextView titleText;
    @BindView(R.id.topbar_left_img)
    public ImageButton topLeftImage;
    @BindView(R.id.exam_title)
    public TextView topicTitleText;
    @BindView(R.id.exam_count_exam)
    public TextView countExamText;
    @BindView(R.id.exam_count_respondence)
    public TextView respondenceText;
    @BindView(R.id.exam_total_point)
    public TextView totalPointText;
    @BindView(R.id.exam_pass_point)
    public TextView passPointText;
    @BindView(R.id.exam_register_man)
    public TextView registerManText;
    @BindView(R.id.exam_register_time)
    public TextView registerTimeText;
    @BindView(R.id.exam_continue)
    public TextView continueButton;
    @BindView(R.id.exam_title_down)
    TextView examTitleDown;
    @BindView(R.id.exam_count_exam_right)
    TextView examCountExamRight;
    @BindView(R.id.exam_count)
    TextView mExamCount;

    private ExamTopic palmExamBean;
    private boolean examFinish = false;
    private List<ExamQuestion> examQuestionList;
    private List<ExamQuestionAnswered> examQuestionAnsweredList;
    private String mDtEnd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_exam);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        titleText.setText("试题");
        titleText.setVisibility(View.VISIBLE);
        topLeftImage.setVisibility(View.VISIBLE);

        initializeViews();
    }

    @Override
    protected void onResume() {
        continueButton.setClickable(false);
        DialogShow.showRoundProcessDialog(this);
        new Thread(new LoadDataThread(INIT_DATA)).start();
        super.onResume();
    }

    private void initializeViews() {
        palmExamBean = (ExamTopic) getIntent().getSerializableExtra("examTopic");
        mDtEnd = getIntent().getStringExtra("dtEnd");
        String str = palmExamBean.getVcTitle();
        if (str.length() > 8) {
            topicTitleText.setText(str.substring(0, 8));
            examTitleDown.setText(str.substring(8, str.length()));
        } else {
            topicTitleText.setText(str);
        }
        registerManText.setText(palmExamBean.getVcRegister());
        passPointText.setText(String.valueOf(palmExamBean.getnPass()));
        totalPointText.setText(String.valueOf(palmExamBean.getnTotal()));
        respondenceText.setText(String.valueOf(palmExamBean.getExamedNumber()));
        registerTimeText.setText(palmExamBean.getDtReg().substring(0, 10));
        countExamText.setText(palmExamBean.getAnswerdNumber() + "");
        examCountExamRight.setText("/" + palmExamBean.getnTopicsTotal());
        mExamCount.setText(palmExamBean.getnTopicsTotal()+"");
    }

    @OnClick({R.id.topbar_left_img, R.id.exam_continue})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.topbar_left_img:
                finish();
                break;
            case R.id.exam_continue:
                switch (palmExamBean.getIsBegin()) {
                    case HttpConstants.ExamTopicType.CONTINUE:
                        new Thread(new LoadDataThread(CONTINUE_EXAM)).start();
                        break;
                    case HttpConstants.ExamTopicType.BEGIN:
                        if (TimeUtils.getTimeBeforeNow(mDtEnd)) {
                            Toast.makeText(this, "此次考试已结束", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        new Thread(new LoadDataThread(START_EXAM)).start();
                        break;
                    case HttpConstants.ExamTopicType.FINISH:
                        new Thread(new LoadDataThread(FINISH_EXAM)).start();
                        break;
                }
                break;
        }
    }

    private void startAnswer() {
        Intent intent = new Intent(this, AnswerActivity.class);
        intent.putExtra("examFinish", examFinish);
        intent.putExtra("examQuestionList", (Serializable) examQuestionList);
        intent.putExtra("examQuestionAnsweredList", (Serializable) examQuestionAnsweredList);
        startActivity(intent);
    }

    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            case INIT_DATA:
                return HttpDataService.getTopicDetail(String.valueOf(palmExamBean.getnId()));
            case START_EXAM:
                return HttpDataService.beginAnswer(String.valueOf(palmExamBean.getnId()));
            case CONTINUE_EXAM:
            case FINISH_EXAM:
                return HttpDataService.getAnswerd(String.valueOf(palmExamBean.getnId()));
        }
        return super.getDataFunction(what, arg1, arg2, obj);
    }

    @Override
    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        DialogShow.closeDialog();
        JSONArray jsonArray = jsonObject.optJSONArray(HttpConstants.OBJECTS);
        switch (msg.what) {
            case INIT_DATA:
                continueButton.setClickable(true);
                examQuestionList = new Gson().fromJson(jsonArray.toString(),
                        new TypeToken<List<ExamQuestion>>() {
                        }.getType());
                continueButton.setText(HttpConstants.ExamTopicType.getExamButtonText(jsonObject.optInt("isBegin")));
                examFinish = palmExamBean.getIsBegin() == HttpConstants.ExamTopicType.FINISH;
                DialogShow.closeDialog();
                break;
            case START_EXAM:
                if (1 == jsonObject.optInt(HttpConstants.ReturnResult.NRES)) {
                    startAnswer();
                }
                break;
            case FINISH_EXAM:
            case CONTINUE_EXAM:
                examQuestionAnsweredList = new Gson().fromJson(jsonArray.toString(),
                        new TypeToken<List<ExamQuestionAnswered>>() {
                        }.getType());
                startAnswer();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(Message msg) {
        switch (msg.what) {
            case 002:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
